var oTable;

$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
    if ( typeof sNewSource != 'undefined' && sNewSource != null ) {
        oSettings.sAjaxSource = sNewSource;
    }
    
    // Server-side processing should just call fnDraw
    if ( oSettings.oFeatures.bServerSide ) {
        this.fnDraw();
        return;
    }
    
    this.oApi._fnProcessingDisplay( oSettings, true );
    var that = this;
    var iStart = oSettings._iDisplayStart;
    var aData = [];
    
    this.oApi._fnServerParams( oSettings, aData );
    
    oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable( oSettings );
        
        /* Got the data - add it to the table */
        var aData =  (oSettings.sAjaxDataProp !== "") ?
        that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
        
        for ( var i=0 ; i<aData.length ; i++ )
        {
            that.oApi._fnAddData( oSettings, aData[i] );
        }
        
        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        
        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
        {
            oSettings._iDisplayStart = iStart;
            that.fnDraw( false );
        }
        else
        {
            that.fnDraw();
        }
        
        that.oApi._fnProcessingDisplay( oSettings, false );
        
        /* Callback user function - for event handlers etc */
        if ( typeof fnCallback == 'function' && fnCallback != null )
        {
            fnCallback( oSettings );
        }
    }, oSettings );
};

$(document).ready(function() {   
    $.blockUI({
        message: "Aguarde un momento por favor"
    });      
    
    menuClass("capacity");        
    reloadTable();
    $.unblockUI();     
    $('#pct_mem').html('0%');    
    $('#pct_cpu').html('0%');    
    
    $('#sld_ram').sGlide({
        height: 10,
        witdh: 20,
        startAt: 0,
        image: '/images/knob.png',	
        colorStart: 'green',
        colorEnd: 'red',	
        drag: function(o){
            var pct = Math.round(o.value)+'%';
            $('#pct_mem').html(pct);
        },
        onButton: function(o){
            var pct = Math.round(o.value)+'%';
            $('#pct_mem').html(pct);
        }
    });
    $('#sld_cpu').sGlide({
        height: 10,
        witdh: 20,
        startAt: 0,
        image: '/images/knob.png',	
        colorStart: 'green',
        colorEnd: 'red',	
        drag: function(o){
            var pct = Math.round(o.value)+'%';
            $('#pct_cpu').html(pct);
        },
        onButton: function(o){
            var pct = Math.round(o.value)+'%';
            $('#pct_cpu').html(pct);
        }
    });
    
    $('#btnguardar').click(guardarconfig);
} );

function reloadTable() {
    if (oTable)  {
        oTable.fnDestroy();
    }
    oTable = $('#capacity_table').dataTable( {                                                
        "oLanguage": {
            "sLengthMenu": "_MENU_ records per page"
        },        
        "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
        "sPaginationType": "bootstrap",
        bLengthChange: false,
        aoColumnsDef: [],            
        "aoColumns": [
        {
            "sTitle": ""
        },        
        {
            "sTitle": "D&iacute;a"
        },
        {
            "sTitle": "Hora inicio"
        },
        {
            "sTitle": "Hora fin"
        },
        {
            "sTitle": "Reserva de CPU"
        },
        {
            "sTitle": "Reserva de memoria"
        }
        ],
        "sAjaxSource": "/admin/capacity/getcapacity/",            
        "fnServerData": function ( sSource, aoData, fnCallback ) {
            $.ajax({
                "url": sSource,
                "data": aoData,
                "success": fnCallback,
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                "cache": false,
                "error": function (xhr, error, thrown) {                        
                    //alertdiv("#div-alert", '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><strong>Error! </strong>' + thrown + '</div>');
                    bootbox.alert('Ocurrio un error inesperado: ' + thrown, function() {
                        });
                }
            });    
        }                
    });                         

}

function addCapacity() {    
    window.location.href = "/admin/capacity/edit"    
}

function cancelar() {    
    $('#btn1').removeClass("active");
    $('#btn2').removeClass("active");
    $('#btn3').removeClass("active");
    $('#btn4').removeClass("active");
    $('#btn5').removeClass("active");
    $('#btn6').removeClass("active");
    $('#btn7').removeClass("active");
    $('#sel-hini-hs').val("00");
    $('#sel-hini-min').val("00");
    $('#sel-hfin-min').val("00");
    $('#sel-hfin-hs').val("00");    
    $('#hdncodigo').val("new");    
    $('#sld_ram').sGlide('startAt', 0);
    $('#sld_cpu').sGlide('startAt', 0);
    $('#pct_mem').html('0%');    
    $('#pct_cpu').html('0%');        
}

function loadConfig(codigo_config) {
    $('#hdncodigo').val(codigo_config);
    $.ajax({
        url: '/admin/capacity/getcapacitybyid/',
        data: {
            'id': codigo_config
        },
        dataType: 'json',
        type: 'post',
        success: function(data) {
            if (data.response === 'error') {
                bootbox.alert(data.message, function() {
                    });
                cancelar();      
            } else {
                $("#hdncodigo").val(data.data.codigo_configuracion_encendido_global);
                $('#sld_cpu').sGlide('startAt',data.data.cantidad_cpu);
                $('#sld_ram').sGlide('startAt',data.data.cantidad_ram);
                $('#pct_mem').html(data.data.cantidad_cpu + '%');    
                $('#pct_cpu').html(data.data.cantidad_ram + '%');
                $('#btn'+ data.data.dia).addClass("active");
                var horainicio = data.data.hora_inicio.split(":", 2);
                var horafin = data.data.hora_fin.split(":", 2);
                $('#sel-hini-hs').val(horainicio[0]);
                $('#sel-hini-min').val(horainicio[1]);
                $('#sel-hfin-hs').val(horafin[0]);
                $('#sel-hfin-min').val(horafin[1]);
            }                                    
        },  
        error: function (xhr, error, thrown) {                                   
            bootbox.alert('Ocurrio un error inesperado: ' + thrown, function() {
                });
            cancelar();      
        }
        
    });    
}

function validar() {
    
    //validacion de que se selecciono un dia
    var diaselect = false;
    var clase;    
    for (var i=1; i<8; i++)
    {
        clase = $('#btn'+i).attr('class');
        if( clase.indexOf("active")>=0 ) {
            diaselect = true;
            break;
        }        
    }    
    if(diaselect == false) {
        bootbox.alert('Debe Seleccionar un dia de la Semana', function() {
            });
        return false;
    }
    
    //validacion de horas (hora inicio menor a hora fin)
    var horaini = parseInt($("#sel-hini-hs").val());
    var horafin = parseInt($("#sel-hfin-hs").val());
    if(horafin < horaini) {
        bootbox.alert('La Hora final debe ser mayor o igual a la hora inicial', function() {
            });
        return false;
    }
    else if(horaini == horafin) {
        var minini = parseInt($("#sel-hini-min").val());
        var minfin = parseInt($("#sel-hfin-min").val());   
        if( minfin <= minini ) {
            bootbox.alert('Los minutos finales deben ser mayores que los minutos iniciales', function() {
                });
            return false;
        }         
    }    
    
    var mem = $('#pct_mem').html().replace("%", "");
    var cpu = $('#pct_cpu').html().replace("%", "");
    
    if(parseInt(mem) == 0) {
        bootbox.alert('El porcentaje de memoria reservado debe ser mayor a 0%', function() {
            });
        return false;
    }
    if(parseInt(cpu) == 0) {
        bootbox.alert('El porcentaje de cpu reservado debe ser mayor a 0%', function() {
            });
        return false;
    }    
    return true;    
}

function getDia() {
    var clase;
    for (var i=1; i<8; i++)
    {
        clase = $('#btn'+i).attr('class');
        if( clase.indexOf("active")>=0 ) {
            return i;
            break;
        }        
    }
    return 0;
}

function getHini() {    
    return $("#sel-hini-hs").val() + ":" + $("#sel-hini-min").val() + ":00" ;
}

function getHfin() {
    return $("#sel-hfin-hs").val() + ":" + $("#sel-hfin-min").val() + ":00" ;
}

function guardarconfig(){
    if(validar()) {
        var codigo_config = $("#hdncodigo").val();        
        if(codigo_config === 'new') {
            //guardar un nuevo valor alerta bootbox
            bootbox.confirm("Esta a punto de guardar un nuevo valor de configuracion. Desea continuar?", function(result) {
                if(result) {
                    saveaction();
                }
            });            
        } else {            
            //guardar un nuevo valor alerta bootbox
            bootbox.confirm("Los valores de la configuracion se modificaran. Desea continuar?", function(result) {
                if(result) {
                    saveaction();
                }
            }); 
        }   
    }
}

function saveaction() {
    var codigo_config = $("#hdncodigo").val();
    var mem = $('#pct_mem').html().replace("%", "");
    var cpu = $('#pct_cpu').html().replace("%", "");
        
    var cpu_save = parseInt(cpu);
    var mem_save = parseInt(mem);
        
    $.ajax({
        url: '/admin/capacity/savecapacity/',
        data: {
            'id': codigo_config,
            'horaini': getHini(),
            'horafin': getHfin(),
            'dia': getDia(),
            'cpu': cpu_save,
            'memoria': mem_save
        },
        dataType: 'json',
        type: 'post',
        success: function(data) {
            if(data.response == 'error') {
                bootbox.alert('Error al guardar configuracion: ' + data.message, function() {
                    cancelar();
                });
            } else {
                bootbox.alert('Datos guardados correctamente ', function() {
                    reloadTable();
                    cancelar();
                });
            }
        },
        error: function(xhr, error, thrown) {                                   
            bootbox.alert('Ocurrio un error inesperado: ' + thrown, function() {
                cancelar();
            });
                  
        }
    });
}

function deleteConfig(codigo_config) {
    
    bootbox.confirm("Esta seguro que desea eliminar esta configuracion?", function(result) {
        if(result) {
            $.ajax({
                url: '/admin/capacity/deletecapacity/',
                data: {
                    'id': codigo_config  
                },
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    if(data.response == 'error') {
                        bootbox.alert('Error al eliminar la configuracion: ' + data.message, function() {
                            cancelar();
                        });
                    } else {
                        bootbox.alert('Configuracion eliminada correctamente', function() {
                            reloadTable();
                            cancelar();
                        });
                    }
                },
                error: function(xhr, error, thrown) {                                   
                    bootbox.alert('Ocurrio un error inesperado: ' + thrown, function() {
                        cancelar();
                    });
                  
                }
            });                
        }
    });            
       
}